package com.hj.dapp.business.brand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hj.dapp.business.brand.mapper.BrandMapper;
import com.hj.dapp.business.brand.model.Brand;
import com.hj.dapp.business.brand.service.BrandService;
import com.hj.dapp.common.request.PageRequest;
import com.hj.dapp.common.util.BrandUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 胡奥程
 * @version 1.0
 * @date 2024/1/22
 */
@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public Brand get(Long id) {
        return brandMapper.selectById(id);
    }

    @Override
    public List<Brand> list() {
        return brandMapper.selectList(null);
    }

    @Override
    public void delete(Long id) {
        brandMapper.deleteById(id);
    }

    @Override
    public IPage<Brand> page(PageRequest<Brand> pageRequest) {
        Page<Brand> page = new Page<>();
        page.setCurrent(pageRequest.getCurrent());
        page.setSize(pageRequest.getSize());
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(pageRequest.getQuery())) {
            if (!ObjectUtils.isEmpty(pageRequest.getQuery().getName())) {
                queryWrapper.like("name", pageRequest.getQuery().getName());
            }
        }
        return brandMapper.selectPage(page,queryWrapper);
    }

    @Override
    public void save(Brand brand, Principal principal) {
        brand.setCode(BrandUtil.generateBrandCode(brand.getName()));
        brand.setCreateBy(principal.getName());
        brand.setCreateTime(LocalDateTime.now());
        brandMapper.insert(brand);
    }

    @Override
    public void edit(Brand brand, Principal principal) {
        brand.setLastUpdateBy(principal.getName());
        brand.setLastUpdateTime(LocalDateTime.now());
        brand.setCode(BrandUtil.generateBrandCode(brand.getName()));
        brandMapper.updateById(brand);
    }
}
